package com.qf.xiaomi.web.filter;

import com.qf.xiaomi.pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

/**
 * 登录过滤器
 * @Created by 马英超 on 2022/8/21 13:55
 * @author： 马英超
 * @version：v1.0
 * @description:
 */
//@WebFilter("/*")
public class LoginFilter implements Filter {
    //定义所有需要排除的url变量
    private static final Set<String> ALLOWED_PATH= Collections.unmodifiableSet(
            new HashSet<>(Arrays.asList("/login.jsp","/register.jsp","/code","/index.jsp","/header.jsp","/registerSuccess.jsp")));


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        final HttpServletRequest request = (HttpServletRequest) servletRequest;
        final HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取http地址
        final String url = request.getRequestURI().substring(request.getContextPath().length()).replaceAll("[/]+$", "");
        final boolean contains = ALLOWED_PATH.contains(url);
        if (contains==true){
            filterChain.doFilter(request,response);
        }else{
            //检查用户是否登录，如果没有登录则跳转至login.jsp页面
            final HttpSession httpSession = request.getSession();
            final User user =(User) httpSession.getAttribute("user");
            if(user!=null)
                filterChain.doFilter(request,response);
            response.sendRedirect("/login.jsp");
        }

    }

    @Override
    public void destroy() {

    }
}
